package cn.nexttec.noteplayer.ui.activities

import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import cn.nexttec.noteplayer.R
import cn.nexttec.noteplayer.common.PERMISSION
import cn.nexttec.noteplayer.common.PermissionHelper
import cn.nexttec.noteplayer.common.Preference
import cn.nexttec.noteplayer.common.debug
import cn.nexttec.noteplayer.databinding.ActivityMainBinding
import cn.nexttec.noteplayer.events.CameraPermissionEvent
import cn.nexttec.noteplayer.events.FileScanDoneEvent
import cn.nexttec.noteplayer.ui.VideoFile.FileFragment
import cn.nexttec.noteplayer.ui.reflow.NoteFragment
import cn.nexttec.noteplayer.ui.settings.PlayerSettingFragment
import cn.nexttec.noteplayer.viewmodels.MainViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private val viewModel:MainViewModel by viewModels()

    @Inject
    lateinit var preference: Preference
    private lateinit var binding: ActivityMainBinding

    // 缓存 Fragment 实例
    private val videoFragment by lazy { FileFragment() }
    private val noteFragment by lazy { NoteFragment() }
    private val settingFragment by lazy { PlayerSettingFragment() }

    private var activeFragment: Fragment = videoFragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        if (EventBus.getDefault().isRegistered(this).not()) {
            EventBus.getDefault().register(this)
        }

        val nomediaFile = File(filesDir, ".nomedia")
        if (nomediaFile.exists().not()){
            nomediaFile.createNewFile()
        }

        initFragments()
        initBottomNavigation()
        window.statusBarColor = ContextCompat.getColor(this, R.color.lt_blue)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

//        installVoskModel()
        viewModel.copyMarkdownTutorial()
    }

    private fun initFragments() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.fragment_container, settingFragment, "personal").hide(settingFragment)
        transaction.add(R.id.fragment_container, noteFragment, "note").hide(noteFragment)
        transaction.add(R.id.fragment_container, videoFragment, "video")
        transaction.commit()
    }

    private fun initBottomNavigation() {
        binding.appBarMain.contentMain.bottomNavView?.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.nav_videos -> {
                    switchFragment(videoFragment)
                    true
                }

                R.id.nav_notes -> {
                    switchFragment(noteFragment)
                    true
                }

                R.id.nav_personal -> {
                    switchFragment(settingFragment)
                    true
                }

                else -> false
            }
        }
    }

    private fun switchFragment(target: Fragment) {
        if (target == activeFragment) return
        supportFragmentManager.beginTransaction()
            .hide(activeFragment)
            .show(target)
            .commit()
        activeFragment = target
        // 统一处理状态栏颜色
        updateUi(target)
    }


    private fun updateUi(target: Fragment) {
        when (target) {
            is PlayerSettingFragment -> {
                window.statusBarColor = Color.WHITE
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                binding.appBarMain.fab?.visibility = View.GONE
                binding.appBarMain.fab?.setOnClickListener {
                    preference.lastPlay?.let{
                        PlayerActivity.start(this@MainActivity, it)
                    }
                }
            }

            is NoteFragment->{
                setDefaultStatusBar()
                binding.appBarMain.fab?.visibility = View.VISIBLE
                binding.appBarMain.fab?.setImageResource(R.drawable.baseline_note_add_24)
                binding.appBarMain.fab?.setOnClickListener {
                    EditorActivity.start(this@MainActivity, 1)
                }
            }
            else -> {

                setDefaultStatusBar()
                binding.appBarMain.fab?.visibility = View.VISIBLE
                binding.appBarMain.fab?.setImageResource(R.drawable.baseline_play_arrow_24)
            }
        }
    }

    private fun setDefaultStatusBar() {
        window.statusBarColor = ContextCompat.getColor(this, R.color.lt_blue)
        window.decorView.systemUiVisibility = 0
//        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    }

    fun setImmersiveMode() {
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                )
        actionBar?.hide()
        supportActionBar?.hide()
    }

//    fun installVoskModel() {
//        lifecycleScope.launch(Dispatchers.IO) {
//            VoskModelInstaller.installIfNeeded(
//                context = this@MainActivity,
//                onSuccess = {
//                    preference.voskModelPath = it.absolutePath
//                    runOnUiThread {
//
//                        Toast.makeText(this@MainActivity, "模型安装完成", Toast.LENGTH_SHORT).show()
//                        Log.i("Vosk", "模型安装完成")
//                    }
//                },
//                onError = {
//                    runOnUiThread {
//                        Toast.makeText(
//                            this@MainActivity,
//                            "模型安装失败: ${it.message}",
//                            Toast.LENGTH_LONG
//                        ).show()
//                        Log.i("Vosk", "模型安装失败:${it.stackTraceToString()}")
//                    }
//                }, onProgress = { fileName, index, total ->
//                })
//        }
//    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == PermissionHelper.REQUEST_CODE_CAMERA) {
            PERMISSION debug "Result:${grantResults[0]}"
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                EventBus.getDefault().post(CameraPermissionEvent(true))
            } else {
                EventBus.getDefault().post(CameraPermissionEvent(false))
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFileScanCompleted(e: FileScanDoneEvent){
        Toast.makeText(this@MainActivity,"文件扫描结束",Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
    }

}
